package com.dailyblue.java.boot.security.project.config;

import com.dailyblue.java.boot.security.project.filter.CheckLoginFilter;
import com.dailyblue.java.boot.security.project.filter.SecurityLoginFilter;
import com.dailyblue.java.boot.security.project.handler.NotLoginHandler;
import com.dailyblue.java.boot.security.project.service.impl.UsersServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

@Configuration
@Slf4j
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private UsersServiceImpl usersServiceImpl;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private NotLoginHandler notLoginHandler;

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(usersServiceImpl).passwordEncoder(getPasswordEncoder());
    }

    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling()
                .authenticationEntryPoint(notLoginHandler)
                .and().csrf().disable() // 关闭 csrf 跨域请求
                .cors().and()    // security允许跨域
                .formLogin()
                .loginProcessingUrl("/user/login")  // 设定登录请求接口
                .usernameParameter("username")
                .passwordParameter("password")
                .permitAll()
                .and()
                .authorizeRequests() // 请求设置
                .antMatchers("/login.html", "/user/login","/powers").permitAll() // 配置不需要认证的接口
                .anyRequest().authenticated() // 任何请求都需要认证
                .and()
                .addFilter(new SecurityLoginFilter(this.authenticationManager(), stringRedisTemplate)) // 认证交给 自定义 TokenLoginFilter 实现
                .addFilter(new CheckLoginFilter(this.authenticationManager(), stringRedisTemplate))
                .httpBasic();
    }

    @Bean(name = "passwordEncoder")
    PasswordEncoder getPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
